package com.easemob.helpdesk.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.easemob.helpdesk.activity.ChatActivity;
import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.bean.User;
import com.easemob.helpdesk.bean.UserInfo;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.R;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DateUtils;
//import com.hyphenate.kefusdk.bean.HDSession;
//import com.hyphenate.kefusdk.bean.HistorySessionEntity;
//import com.hyphenate.kefusdk.bean.Summary;
import com.hyphenate.kefusdk.entity.HistorySessionEntity;
import com.hyphenate.kefusdk.entity.Summary;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by liyuzhao on 16/3/7.
 */
public class HistoryListHolder extends BaseViewHolder<HistorySessionEntity> {

    ImageView ivOriginType;
    ImageView avatar;
    public TextView tvName;
    TextView tvTime;
    TextView tvAgent;
    TextView tvSummaryCount;
    TextView tvSummary;
    ImageView vipIcon;

    public HistoryListHolder(ViewGroup parent) {
        super(parent, R.layout.item_history_session);
        ivOriginType = $(R.id.originType);
        avatar = $(R.id.avatar);
        tvName = $(R.id.name);
        tvTime = $(R.id.time);
        tvAgent = $(R.id.tv_agent);
        tvSummaryCount = $(R.id.tv_summary_count);
        tvSummary = $(R.id.tv_summary);
        vipIcon = $(R.id.vip_icon);
    }

    @Override
    public void setData(HistorySessionEntity data) {
        super.setData(data);
        if(data == null){
            return;
        }
        if(data.visitorUser != null){
            tvName.setText(data.visitorUser.getNicename());
        }

        getUserInfo(data);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        try {
            tvTime.setText(DateUtils.getTimestampString(dateFormat.parse(data.startDateTime)));

        } catch (ParseException e) {
            e.printStackTrace();
        }

        if(!TextUtils.isEmpty(data.agentUserNiceName)){
            tvAgent.setText("客服-"+data.agentUserNiceName);
        }



       List<Summary> summaryList =  data.summarys;
        if(summaryList != null && summaryList.size() > 0){
//            tvSummary.setVisibility(View.VISIBLE);
//            tvSummaryCount.setVisibility(View.VISIBLE);

            Summary summary = summaryList.get(0);
            int roundRadius = CommonUtils.convertDip2Px(getContext(), 4);//圆角半径
//            int fillColor = Color.parseColor("#DFDFE0");//内部填充颜色
            GradientDrawable gradientDrawable = new GradientDrawable();//创建drawable
            gradientDrawable.setColor(getColorString(summary.color));
            gradientDrawable.setCornerRadius(roundRadius);
            String parentName = TextUtils.isEmpty(summary.rootName) ? "" : summary.rootName + " · ";
            tvSummary.setText(parentName + summary.name);
            tvSummary.setBackgroundDrawable(gradientDrawable);
            if(summaryList.size() > 1){
                tvSummaryCount.setText("("+summaryList.size()+")");
            }else {
                tvSummaryCount.setText("");
            }

        }else{
            tvSummary.setVisibility(View.GONE);
            tvSummaryCount.setVisibility(View.GONE);
        }
//
//
//        String summarysDetail = data.summarysDetail;
//        if (!TextUtils.isEmpty(summarysDetail)) {
//            tvMessage.setText("会话标签：" + data.summarysDetail);
//        }
//        int strokeWidth = 5;//边框宽度
//        int roundRadius = 15;//圆角半径
//        int strokeColor = Color.parseColor("#2E3135");//边框颜色
//        int fillColor = Color.parseColor("#DFDFE0");//内部填充颜色
//
//        GradientDrawable gradientDrawable = new GradientDrawable();//创建drawable
//        gradientDrawable.setColor(fillColor);
//        gradientDrawable.setStroke(strokeWidth, strokeColor);
//        setBackgroundDrawable(gradientDrawable);
    }

    private void getUserInfo(final HistorySessionEntity data) {
        OkHttpClient okHttpClient = new OkHttpClient();
        String val = data.visitorUser.getUsername();

        if(!TextUtils.isEmpty(val) && val.contains("#")){
            String uid = val.split("#")[0];
            ApiService apiService = HKHttpUtils.getApiService();
            retrofit2.Call<BaseResponse<User>> call = apiService.getUserById(MainActivity.ticket, String.valueOf(uid));
            call.enqueue(new HKResponseResultCallBack<User>() {
                @Override
                public void onSuccess(User user) {
                    if(user != null){
                        if(!((Activity) getContext()).isDestroyed() && !TextUtils.isEmpty(user.getWxHeader())){
                            Glide.with(getContext()).load(user.getWxHeader())
                                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.drawable.default_customer_avatar).error(R.drawable.default_customer_avatar)
                                    .into(avatar);
                        }

                        if(!TextUtils.isEmpty(user.getName())){
                            tvName.setText(user.getName());
                        }else{
                            tvName.setText(data.visitorUser.getNicename());
                        }
                        if (user.getIsVip() == 1){
                            vipIcon.setVisibility(View.VISIBLE);
                        }else {
                            vipIcon.setVisibility(View.GONE);
                        }
                    }
                }

                @Override
                public void onGetDataFailed(int cd, String msg) {
                    Toast.makeText(getContext(), "请求失败:"+msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailed(retrofit2.Call call, Throwable t) {
                    Toast.makeText(getContext(), "请求失败", Toast.LENGTH_SHORT).show();
                }
            });
//            RequestBody body = new FormBody.Builder()
//                    .add("uid", String.valueOf(uid))
//                    .build();
//
//            Request request = new Request.Builder()
//                    .url(BuildConfig.API_URL + "account/findUserById")
//                    .post(body)
//                    .build();
//
//            Call call = okHttpClient.newCall(request);
//
//            call.enqueue(new Callback() {
//                @Override
//                public void onFailure(Call call, IOException e) {
//                    e.printStackTrace();
//                    ((Activity)getContext()).runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(getContext(), "请求失败", Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                }
//
//                @Override
//                public void onResponse(Call call, Response response) throws IOException {
//
//                    final String res = response.body().string();
//                    final UserInfo result = CommonUtils.parseJsonWithGson(res, UserInfo.class);
//
//                    ((Activity)getContext()).runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if(result.getData() != null){
//                                if(!((Activity) getContext()).isDestroyed() && !TextUtils.isEmpty(result.getData().getWxHeader())){
//                                    Glide.with(getContext()).load(result.getData().getWxHeader()).asBitmap()
//                                            .diskCacheStrategy(DiskCacheStrategy.SOURCE).placeholder(R.drawable.default_customer_avatar).error(R.drawable.default_customer_avatar)
//                                            .into(avatar);
//                                }
//
//                                if(!TextUtils.isEmpty(result.getData().getName())){
//                                    tvName.setText(result.getData().getName());
//                                }else{
//                                    tvName.setText(data.visitorUser.getNicename());
//                                }
//                            }
//                        }
//                    });
//
//                }
//            });

        }




    }


    private int getColorString(int color){
        String strColor;
        if(color == 0){
            strColor = "#000000";
        }else if(color == 255){
            strColor = "#ffffff";
        }else{
            strColor = "#"+Integer.toHexString(color);
            strColor = strColor.substring(0,7);
        }
        return Color.parseColor(strColor);
    }



}
